#!/bin/bash  
  
# 脚本时间戳，用于日志记录  
# time: 20240713  
# 优化log及结果收集流程

source ./base/config.cfg
  
# 接收任务名称作为脚本的第一个参数  
TaskName=$1  
# 远程服务器的IP地址


mkdir -p "$DataPath"
mkdir -p "$BasePath"
mkdir -p "$LogPath"
mkdir -p "$ResultPath"

# echo  $DataPath
# echo  $BasePath
# echo  $LogPath
# echo  $ResultPath
# echo  $ServerIp

#后续优化log打包流程及结果收集备份

# 远程数据文件名（在远程服务器上的路径）
RemoteDataFile="/opt/opn_task/$TaskName/Common/TestMachineBaseInfoTable.txt"
# 本地数据文件名（脚本将复制到本地的路径）  
DataFile="$DataPath/TestMachineBaseInfoTable.txt"

# 使用sshpass和scp从远程服务器复制测试机器文件信息（考虑使用密钥认证）  
sshpass -p 'hygon123;' scp -r -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@$ServerIp:$RemoteDataFile $DataFile
  
# 检查文件是否成功复制  
if [ $? -ne 0 ] || [ ! -f "$DataFile" ]; then
    echo "'$DataFile' not exist or scp failed."
    exit 1
fi


awk 'NR>1' "$DataPath/TestMachineBaseInfoTable.txt" > "$DataPath/TestMachineBaseInfoTable1.txt"
# 机器名进行排序
sort -k1 "$DataPath/TestMachineBaseInfoTable1.txt" > $DataPath/TestMachineBaseInfoTable2.txt
awk '{print $6}' "$DataPath/TestMachineBaseInfoTable2.txt" > "$DataPath/ip.txt"
MachineNum=`cat $DataPath/TestMachineBaseInfoTable2.txt | wc -l`


# 读取IP地址并执行脚本
while IFS= read -r ip
do
    MachineNo=`cat $DataPath/TestMachineBaseInfoTable.txt | grep -i $ip | awk '{print $1}'`
    echo "Processing Machine: $MachineNo and IP: $ip"
    # 构造日志文件名
    logfile="$LogPath/collect_log_$MachineNo.log"
    # 使用nohup在后台运行脚本，并将输出重定向到日志文件 
    # echo $ScriptTotalPath/collect.sh
    sudo nohup bash $ScriptTotalPath/collect.sh "$ip" > "$logfile" 2>&1 &
    # 等待一会儿
    sleep 2
done < "$DataPath/ip.txt"


while true; do
    # 文件数量判断判断
    ScpFileNum=`ls $ResultPath  | wc -l`
    echo  "MachineNum：'$MachineNum'  and   ScpFileNum：'$ScpFileNum'"
    if [ "$MachineNum" -eq "$ScpFileNum" ];then
      # echo "kill begin"
      pkill -f "collect*.sh"
      # echo "kill end"
      break
      # sshpass -p 'hygon123;' ssh -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null  root@10.62.46.11 “pkill -f collect*.sh”
    else
      sleep 2
    fi
done


  
echo "All IPs have been processed."